<?php
if(!defined('IN_DISCUZ')) exit('Access Denied');

global $_G;
$uid = $_G['uid'];
if(!$uid) {
    $data = [
        'success' => false,
        'message' => '请先登录'
    ];
    echo json_encode($data);
    exit;
}

if(!submitcheck('formhash')) {
    $data = [
        'success' => false,
        'message' => '请求来源验证失败'
    ];
    echo json_encode($data);
    exit;
}



// 获取表模型
$sign_table = C::t('#erling_qd#sings');
$sign_data = $sign_table->fetch_by_uid($uid);
// 检查是否已经签到
$is_signed = false;
$latest_sign = $sign_table->fetch_by_uid($uid);
if($latest_sign && date('Y-m-d', $latest_sign['dateline']) == date('Y-m-d')) {
    $is_signed = true;
    $continuous_days = $latest_sign['continuous']; 
}

if(!$is_signed) {
    $continuous_days = 1; // 默认连续签到天数为1
    // 检查昨天是否签到过
    if($sign_data && date('Y-m-d', $sign_data['dateline']) == date('Y-m-d', strtotime('-1 day'))) {
        $continuous_days = $sign_data['continuous'] + 1;
    }
    // 如果昨天没签到，但上次签到不是昨天，检查是否中断过
    elseif($sign_data && $sign_data['continuous'] > 0 && date('Y-m-d', $sign_data['dateline']) != date('Y-m-d', strtotime('-1 day'))) {
        $continuous_days = 1; // 中断后重置为1
    }
    // 获取积分配置
    require_once DISCUZ_ROOT.'./source/plugin/erling_qd/table/table_erling_qd_configs.php';
    $credit_config = C::t('erling_qd_configs')->fetch_by_keys([
        'credit', 
        'extcredits'
    ]);

    if($credit_config['credit']) {
        $credit_range = json_decode($credit_config['credit']['value'], true);
        $credit = rand($credit_range[0], $credit_range[1]); // 生成随机积分
    } else {
        die('积分配置不存在，请重新安装插件');
    }

    $extcredits = 'extcredits2';
    if($credit_config['extcredits']) {
        $extcredits = 'extcredits'.$credit_config['extcredits']['value'];    
    }

    // 1. 更新用户积分 (extcredits2)
    $update_credit = DB::query("UPDATE %t SET $extcredits=$extcredits+%d WHERE uid=%d", 
        array('common_member_count', $credit, $uid));

    // 2. 记录积分日志
    $logid = DB::insert('common_credit_log', array(
        'uid' => $uid,
        'operation' => 'RUL', // 签到操作类型
        'relatedid' => 0,
        'dateline' => time(),
        $extcredits => $credit
    ), true);

    // 3. 记录积分日志详情
    DB::insert('common_credit_log_field', array(
        'logid' => $logid,
        'title' => '每日签到奖励',
        'text' => '用户通过每日签到获得积分'
    ));

    // 4. 记录签到记录
    $sign_table->insert(array(
        'uid' => $uid, 
        'credit' => $credit,
        'dateline' => time(), 
        'continuous' => $continuous_days
    ));
}

try {
    if(!$is_signed) {
        // 所有签到逻辑代码
    }
    
    $data = [
        'success' => true,
        'credit' => $credit ?? 0,
        'continuous_days' => $continuous_days,
        'message' => '签到成功'
    ];
} catch(Exception $e) {
    $data = [
        'success' => false,
        'message' => '系统错误: '.$e->getMessage()
    ];
}

header('Content-Type: application/json');
echo json_encode($data);
exit;